package caches

import (
	"encoding/json"
	"github.com/astaxie/beego/cache"
	_ "github.com/astaxie/beego/cache/redis"
	"github.com/astaxie/beego/config"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"time"
)

type AccessToken struct {
	cache.Cache
}

func (self *AccessToken) FetchAccessToken() (interface{}, bool) {
	client := &http.Client{Timeout: time.Duration(10 * time.Second)}
	Base, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	wxConfig, readError := config.NewConfig("ini", filepath.Join(Base, "conf/weixin.conf"))
	if readError != nil {
		panic("找不到配置文件")
	}
	response, error := client.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxConfig.String("appid") + "&secret=" + wxConfig.String("appsecret"))
	defer response.Body.Close()
	res, error := ioutil.ReadAll(response.Body)
	if error != nil {
		return nil, true
	}
	resultJsonMap := map[string]interface{}{}
	defodeError := json.Unmarshal(res, &resultJsonMap)
	if defodeError != nil {
		return nil, true
	}
	return resultJsonMap, false
}

func (self *AccessToken) GetAccessToken() string {
	res := self.Get("access_token")
	if res != nil && len(res.([]byte)) != 0 {
		return string(res.([]byte))
	}
	ticket, errors := self.FetchAccessToken()
	if !errors {
		newTicket := ticket.(map[string]interface{})
		self.Put("access_token", newTicket["access_token"], time.Duration(7200*time.Second))
		return newTicket["access_token"].(string)
	}
	return ""
}

func CreateAccesstokenSession() *AccessToken {
	ca, error := cache.NewCache("redis", `{"conn":":6379","dbNum":"0"}`)
	if error != nil {
		panic("链接redis服务器失败")
	}
	return &AccessToken{Cache: ca}
}
